package com.hhs.storage.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Auther: shadow
 * @Date: 2018/10/6 13:58
 * @Description:
 * jxcmenu类的属性icon会与zTree的冲突，所以重新定义此类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TreeMenu {
    private String id;
    private String pid;
    private String name;
    private int order;

    private static Comparator<TreeMenu> order() {
        Comparator<TreeMenu> comparator = new Comparator<TreeMenu>() {
            @Override
            public int compare(TreeMenu o1, TreeMenu o2) {
                if (o1.getOrder() != o2.getOrder()) {
                    return o1.getOrder() - o2.getOrder();
                }
                return 0;
            }
        };

        return comparator;
    }

    /**
     *
     * @param allMenu
     * @return 对菜单进行排序，一级菜单的排序受到sql id的影响,无法正确排序，所以重新排序一级菜单
     */
    public static List<TreeMenu> orderAll(List<TreeMenu> allMenu)  {
        //获取一级菜单  
        List<TreeMenu> rootMenu = new ArrayList<TreeMenu>();
        //非一级菜单已由sql语句进行排序
        List<TreeMenu> sonMenu = new ArrayList<TreeMenu>();
        for (TreeMenu nav : allMenu) {
            if (StringUtils.isEmpty(nav.getPid()) || "0".equals(nav.getPid())) {//父节点是0的，为根节点。        
                rootMenu.add(nav);
            }else{
                sonMenu.add(nav);
            }
        }
        //对一级菜单进行排序
        Collections.sort(rootMenu, order());
        //添加下级菜单 
        for (TreeMenu nav : sonMenu) {
            rootMenu.add(nav);
        }
        return rootMenu;
    }

    /**
     *  菜单对象的转换，供zTree使用
     * @param list
     * @return
     */
    public static List<TreeMenu> formatJxcMenu(List<JxcMenu> list){
        List<TreeMenu> result = new ArrayList<>();
        for (JxcMenu jxcMenu : list) {
            result.add(new TreeMenu(jxcMenu.getId(),jxcMenu.getPid(),jxcMenu.getText(),jxcMenu.getOrder()));
        }
        result = orderAll(result);
        return result;
    }
}
